package com.dragee.modules.work.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragee.common.P;
import com.dragee.common.PageUtils;
import com.dragee.common.R;
import com.dragee.config.exception.BusinessException;
import com.dragee.constants.CommonConstants;
import com.dragee.modules.sys.entity.LoginUser;
import com.dragee.modules.sys.po.RolePo;
import com.dragee.modules.work.dao.TeamAthleteDao;
import com.dragee.modules.work.entity.TeamAthleteEntity;
import com.dragee.modules.work.entity.TeamEntity;
import com.dragee.modules.work.service.TeamAthleteService;
import com.dragee.modules.work.service.TeamService;
import com.dragee.utils.IdCardUtil;
import com.dragee.utils.LoginUserUtil;
import com.dragee.utils.StringUtils;
import com.dragee.utils.WrapperUtil;
import com.dragee.utils.excel.CommonListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("teamAthleteService")
public class TeamAthleteServiceImpl extends ServiceImpl<TeamAthleteDao, TeamAthleteEntity> implements TeamAthleteService {


    @Resource
    private TeamAthleteDao teamAthleteDao;

    private String business = "teamAthlete";
    @Autowired
    private TeamService teamService;
    /**
    * 列表
    */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {


        int limit = params.get(CommonConstants.LIMIT) == null
                ?CommonConstants.LIMIT_SIZE:Integer.parseInt(params.get(CommonConstants.LIMIT).toString());
        int start = params.get(CommonConstants.START) == null
                ?CommonConstants.START_SIZE:Integer.parseInt(params.get(CommonConstants.START).toString());
        QueryWrapper<TeamAthleteEntity> wrapper =
                WrapperUtil.getWrapper(business, params, TeamAthleteEntity.class);

        LoginUser loginUser = LoginUserUtil.getLoginUser();
        RolePo role = loginUser.getRole();
        if (role.getRoleKey().equals("duiwu")) {
            // 队伍登录
            TeamEntity team = teamService.getTeamByUserId(loginUser.getUserId().toString());
            wrapper.eq("teamKey", team.getId());
            wrapper.in("applyStatus", "待通过", "已加入");
        }
        if (role.getRoleKey().equals("jiazhang")) {
            // 队伍登录
            wrapper.eq("userId", loginUser.getUserId().toString());
        }
        IPage<TeamAthleteEntity> page = new Page<>(start, limit);
        page = baseMapper.selectPage(page, wrapper.select());
        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R importData(MultipartFile file) throws IOException {
        //填充对应词典 sex: (1:男, 2:女)
        Map<String, Map<String,Object>> map = new HashMap<>();
        //解析器
        CommonListener<TeamAthleteEntity> commonListener
                = new CommonListener<>(map, TeamAthleteEntity.class,this::excelBatch);
        EasyExcel.read(file.getInputStream())
                .head(TeamAthleteEntity.class)
                .registerReadListener(commonListener)
                .sheet()
                .doRead();
        List<String> msgList = commonListener.getMsgList();
        if(msgList.size()>0){
            return R.error(StringUtils.join(msgList,","));
        }
        return R.ok();
    }

    /** 导入执行入库方法
     * @param datas
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean excelBatch (List<TeamAthleteEntity> datas) {
        Long userId = LoginUserUtil.getLoginUserId();
        TeamEntity team = teamService.getTeamByUserId(userId.toString());
        if (team == null) {
            return true;
        }
        Object obj = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (int i = 0; i < datas.size(); i++) {
            TeamAthleteEntity data = datas.get(i);
            P.green("【导入身份证号】"+data.getIdCard());
            if (!IdCardUtil.isIdCard(data.getIdCard())) {
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(obj);
                throw new BusinessException(String.format("导入异常: 第%s行,身份证号不合法", i+2));
            }
            data.setAge(IdCardUtil.getAgeFromIdCard(data.getIdCard()) + "");
            data.setSex(IdCardUtil.getSexFromIdCard(data.getIdCard()));
            data.setTeamKey(team.getId().toString());
            data.setTeamId(team.getCode());
            data.setApplyStatus("已加入");
            saveOrUpdate(data);

        }
        return true;
    }

    public static void main(String[] args) {
        if (!IdCardUtil.isIdCard("3702841994102808111")) {
            System.out.println(1);
        }
        System.out.println(IdCardUtil.isIdCard("370126199303090812"));
        System.out.println(IdCardUtil.isIdCard("370284199410280811"));
    }

    @Override
    public String getAthleteIdsByNames(String teamId, String names) {
        String[] nameArr = names.split(",");
        List<String> ids = new ArrayList<>();
        for (String name : nameArr) {
            TeamAthleteEntity athleteEntity = getOne(new QueryWrapper<TeamAthleteEntity>()
                    .eq("teamKey", teamId)
                    .eq("name", name), false);
            if (athleteEntity != null) {
                ids.add(athleteEntity.getId() + "");
            }
        }
        return ArrayUtil.join(ids.toArray(), ",");
    }
}